package cloud.tianai.ram.policy.demo;

import cloud.tianai.ram.policy.spring.CurrentUserStatementProvider;
import cloud.tianai.ram.policy.core.comparator.DefaultStatementComparator;
import cloud.tianai.ram.policy.core.Effect;
import cloud.tianai.ram.policy.core.Statement;
import cloud.tianai.ram.policy.core.condition.Condition;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
public class DemoCurrentUserPermissionProvider implements CurrentUserStatementProvider {
    @Override
    public List<Statement> getCurrentUserStatementList(MethodInvocation invocation) {

        Statement statement = new Statement();
        // 拒绝 zb:project:* 下的资源访问
        statement.setEffect(Effect.Deny);
        statement.setActionList(Arrays.asList("*"));
        statement.setResourceList(Arrays.asList("zb:project:*"));
        statement.setConditionList(null);

        // 允许 zb:qiyeguanli:qiyexingxi:** zb:zhuanjiaku:zhuanjiachouqu:* 下的资源访问 且条件通过(Condition 条件是自定义的校验逻辑)
        Statement statement2 = new Statement();
        statement2.setEffect(Effect.Allow);
        statement2.setActionList(Arrays.asList("post", "put"));
        statement2.setResourceList(Arrays.asList("zb:qiyeguanli:qiyexingxi:**","zb:zhuanjiaku:zhuanjiachouqu:*"));
        Condition condition = new Condition();
        condition.setOperationType("ip");
        condition.setKey("ip");
        condition.setValueList(Arrays.asList("127.0.0.1"));

        // 拒绝 zb:zhuanjiaku:zhuanjiachouqu:1, zb:zhuanjiaku:zhuanjiachouqu:aa, zb:zhuanjiaku:zhuanjiachouqu:22 这三个资源的 post操作访问
        Statement statement3 = new Statement();
        statement3.setEffect(Effect.Deny);
        statement3.setActionList(Arrays.asList("post"));
        statement3.setResourceList(Arrays.asList("zb:zhuanjiaku:zhuanjiachouqu:1", "zb:zhuanjiaku:zhuanjiachouqu:aa", "zb:zhuanjiaku:zhuanjiachouqu:22"));
        statement3.setConditionList(null);

        List<Statement> statementList = new ArrayList<>();
        statementList.add(statement2);
        statementList.add(statement);
        statementList.add(statement3);
        // 排序
        DefaultStatementComparator.INSTANCE.sort(statementList);
        return statementList;
    }
}
